//
//  SN_NewspaperInfoViewController.m
//  Shiyun_Newspaper
//
//  Created by Sylar on 2017/6/20.
//  Copyright © 2017年 ShiYun. All rights reserved.
//

#import "SN_NewspaperInfoViewController.h"
#import "SN_Question_ResolveController.h"
#import "SDProgressView.h"
#import <MediaPlayer/MediaPlayer.h>
#import <AVFoundation/AVFoundation.h>
@interface SN_NewspaperInfoViewController ()<UIScrollViewDelegate>
{
    CGFloat offset;
    UIButton *answerBtn;
    BOOL isCollection;
    UIButton *collectBtn;
    BOOL isPlay;
    NSString * learing;
    NSInteger courseId;
}

@property (nonatomic, strong) UIScrollView *paperScrollView;
@property (nonatomic, strong) UIScrollView *answerScroll;
@property (nonatomic, strong) NSMutableArray *paperInfoArr;
@property (nonatomic, strong) NSMutableArray *answerArr;
@property (nonatomic, strong) NSMutableArray *bottomBtnArr;

@property (nonatomic, strong) AVPlayer *player;

@end

@implementation SN_NewspaperInfoViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    if (self.paperModel) {
        self.navBar.navigationItem.title = [NSString stringWithFormat:@"第%ld期 %@",(long)self.paperModel.phase,self.paperModel.newsname];
        self.newsid = [NSString stringWithFormat:@"%ld",(long)self.paperModel.newid];
    }else {
        self.navBar.navigationItem.title = @"读报";
    }
    
    collectBtn = [UIButton buttonWithType:(UIButtonTypeCustom)];
    [collectBtn setFrame:CGRectMake(0, 0, 44, 44)];
    [collectBtn setImageEdgeInsets:UIEdgeInsetsMake(0, 10, 0, -10)];
    [collectBtn setImage:[UIImage imageNamed:@"unCollection"] forState:(UIControlStateNormal)];
    [collectBtn addTarget:self action:@selector(collectionAction) forControlEvents:(UIControlEventTouchUpInside)];
    
    UIBarButtonItem *right = [[UIBarButtonItem alloc]initWithCustomView:collectBtn];
    
    self.navBar.navigationItem.rightBarButtonItem = right;
    
    offset = 0.0;
    
    [self.view addSubview:self.paperScrollView];
    
    [self getPaperInfo];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Method

-(void)handleDoubleTap:(UIGestureRecognizer *)gesture{
    
    float newScale = [(UIScrollView*)gesture.view.superview zoomScale] * 1.5;
    CGRect zoomRect = [self zoomRectForScale:newScale  inView:(UIScrollView*)gesture.view.superview withCenter:[gesture locationInView:gesture.view]];
    [(UIScrollView*)gesture.view.superview zoomToRect:zoomRect animated:YES];
}


- (CGRect)zoomRectForScale:(float)scale inView:(UIScrollView*)scrollView withCenter:(CGPoint)center {
    
    CGRect zoomRect;
    
    zoomRect.size.height = [scrollView frame].size.height / scale;
    zoomRect.size.width  = [scrollView frame].size.width  / scale;
    
    zoomRect.origin.x    = center.x - (zoomRect.size.width  / 2.0);
    zoomRect.origin.y    = center.y - (zoomRect.size.height / 2.0);
    
    return zoomRect;
}

- (void)creatBottomView:(BOOL)flag {
    
    UIView *bottomView = [[UIView alloc]initWithFrame:CGRectMake(0, SCREENHEIGH - 53, SCREENWIDTH, 53)];
    [bottomView setBackgroundColor:[UIColor colorWithHexString:@"fb524a"]];
    bottomView.alpha = 1;
    [self.view addSubview:bottomView];
    
    answerBtn = [UIButton buttonWithType:(UIButtonTypeCustom)];
    [answerBtn setTitle:@"答案" forState:(UIControlStateNormal)];
    [answerBtn setFrame:CGRectMake(15, bottomView.y, 40, 53)];
    [answerBtn.titleLabel setFont:[UIFont systemFontOfSize:17]];
    [answerBtn setTitleColor:[UIColor whiteColor] forState:0];
    [answerBtn addTarget:self action:@selector(answerAction) forControlEvents:(UIControlEventTouchUpInside)];
    [self.view addSubview:answerBtn];
    
    self.bottomBtnArr = [[NSMutableArray alloc]init];
    for (int i = 0; i < self.paperInfoArr.count; i++) {
        
        UIButton *btn = [UIButton buttonWithType:(UIButtonTypeCustom)];
        btn.tag = i;
        [btn setFrame:CGRectMake(60+i*30, bottomView.y, 30, 53)];
        [btn setTitleColor:i == 0 ?[UIColor blackColor]:[UIColor whiteColor] forState:(UIControlStateNormal)];
        [btn setTitle:[NSString stringWithFormat:@"%d",i+1] forState:(UIControlStateNormal)];
        [btn addTarget:self action:@selector(scrollTopage:) forControlEvents:(UIControlEventTouchUpInside)];
        
        [self.view addSubview:btn];
        
        [self.bottomBtnArr addObject:btn];
        
    }
    
    UIButton *playerBtn = [UIButton buttonWithType:(UIButtonTypeCustom)];
    [playerBtn setFrame:CGRectMake(SCREENWIDTH  -15 - 31, bottomView.y+12, 31, 31)];
    [playerBtn setImage:[UIImage imageNamed:@"action_nor"] forState:UIControlStateNormal];
    [playerBtn setImage:[UIImage imageNamed:@"stop_nor"] forState:UIControlStateSelected];
    [playerBtn addTarget:self action:@selector(stareOrFinishedAction:) forControlEvents:UIControlEventTouchUpInside];
    [playerBtn setHidden: flag];
    [self.view addSubview:playerBtn];
    
    UIButton *rightBtn = [UIButton buttonWithType:(UIButtonTypeCustom)];
    [rightBtn setFrame:CGRectMake(SCREENWIDTH - 87, bottomView.y+12, 72, 26)];
    [rightBtn setTitleColor:[UIColor whiteColor] forState:0];
    [rightBtn setTitle:@"查看解题" forState:0];
    [rightBtn.titleLabel setFont:[UIFont systemFontOfSize:15]];
    rightBtn.layer.cornerRadius = 3;
    rightBtn.layer.borderWidth = 1;
    rightBtn.layer.borderColor = [[UIColor whiteColor] CGColor];
    [rightBtn addTarget:self action:@selector(answerInfoAction) forControlEvents:(UIControlEventTouchUpInside)];
    if (_paperModel.ishavething == 1) {
        
         [self.view addSubview:rightBtn];
    }
   
    
}

- (AVPlayer *)player
{
    
    if (_player == nil) {
        
        AVPlayerItem *item = [[AVPlayerItem alloc] initWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@%@",REQUESTPLAYER,learing]]];
        //通过AVPlayerItem初始化player
        _player = [[AVPlayer alloc] initWithPlayerItem:item];
    }
    
    return _player;
}
- (void)stareOrFinishedAction:(UIButton *)sender
{
    isPlay = !isPlay;
    sender.selected = isPlay;
    
    NSLog(@"learing= %@  learing.l=%lu",learing,(unsigned long)learing.length);

    if (isPlay) {
            
        [self.player play];
    }else
    {
        [self.player pause];
    }
    
    
    
    // 弹出播放器,并播放视频
//    [self presentViewController:self.playerVC animated:YES completion:nil];
}
- (void)createMPPlayerController:(NSString *)sFileNamePath {

//    // 1.创建视频的资源
//    NSURL *url = [NSURL URLWithString:sFileNamePath];
//    // 2.创建播放器
//    _playerVC = [[MPMoviePlayerViewController alloc] initWithContentURL:url];
    
    
}
- (void)answerInfoAction {
    NSLog(@"查看解题");
    
    SN_NewspaperModel *paperModel = [self.paperInfoArr firstObject];
    if (paperModel.ishavething == 1) {
        SN_Question_ResolveController *vc = [[SN_Question_ResolveController alloc]init];
        vc.newsId = self.newsid;
        
        [self.navigationController pushViewController:vc animated:YES];
    }else {
        UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"暂无解题资料，工作人员正在处理中" message:nil delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        [alert show];
    }
    
    
}

- (void)answerAction {
    
    for (UIButton *btn in self.bottomBtnArr) {
        [btn setTitleColor:[UIColor whiteColor] forState:(UIControlStateNormal)];
    }
    
    self.answerScroll.x = self.paperScrollView.contentOffset.x;
    self.answerScroll.contentOffset = CGPointMake(0, 0);
    self.answerScroll.hidden = NO;
    self.paperScrollView.scrollEnabled = NO;
    [answerBtn setTitleColor:[UIColor blackColor] forState:(UIControlStateNormal)];
}
//点击方法
- (void)scrollTopage:(id)sender {
    
    UIButton *button = (UIButton *)sender;
    
    [self.paperScrollView setContentOffset:CGPointMake(button.tag*SCREENWIDTH, 0) animated:YES];
    self.paperScrollView.scrollEnabled = YES;
    self.answerScroll.hidden = YES;
    [answerBtn setTitleColor:colorFromHex(@"ffffff") forState:(UIControlStateNormal)];
    
    for (UIButton *btn in self.bottomBtnArr) {
        [btn setTitleColor:btn.tag == button.tag?[UIColor blackColor]:[UIColor whiteColor] forState:(UIControlStateNormal)];
    }
}

//因为hud消失有延迟，所以延时执行这个方法
- (void)emptyImg {
    
    UIImageView *emptyImg = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, 180, 140)];
    [emptyImg setImage:[UIImage imageNamed:@"unContent"]];
    emptyImg.center = self.view.center;
    
    [self.view addSubview:emptyImg];
}

#pragma mark - ScrollView delegate
-(UIView *)viewForZoomingInScrollView:(UIScrollView *)scrollView{
    
    for (UIView *v in scrollView.subviews){
        return v;
    }
    return nil;
}

-(void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView{
    
    if (scrollView == self.paperScrollView){
        CGFloat x = scrollView.contentOffset.x;
        
        int p = x/SCREENWIDTH;
        for (UIButton *btn in self.bottomBtnArr) {
            [btn setTitleColor:btn.tag == p?[UIColor blackColor]:[UIColor whiteColor] forState:(UIControlStateNormal)];
        }
        
        if (x==offset){
            
        }else {
            offset = x;
            for (UIScrollView *s in scrollView.subviews){
                if ([s isKindOfClass:[UIScrollView class]]){
                    [s setZoomScale:1.0];
                }
            }
        }
    }
}

#pragma mark - ReloadDataDelegate

- (void)reloadCurrentData {
    
    [self.networkErrorView hideEmptyImage];
    [self getPaperInfo];
    
}

#pragma mark - Requset

- (void)getPaperInfo {
    
    NSMutableDictionary *param = [[NSMutableDictionary alloc]init];
    
    [param setObject:self.newsid forKey:@"newsid"];
    [param setObject:@"api_szb_newspiclist" forKey:@"Method"];
    
    [Utils getWithparameters:param showHUD:NO success:^(NSInteger recode, id jsonObject) {
        
        //[Utils hideHUD];
        NSDictionary *dict = (NSDictionary *)jsonObject;
        
        NSArray *arr = [dict objectForKey:@"re_data"];
        
        if (arr.count == 0) {
            
            [self performSelector:@selector(emptyImg) withObject:nil afterDelay:0.2];
            collectBtn.hidden = YES;
            return;
        }
        collectBtn.hidden = NO;
        self.paperInfoArr = [[NSMutableArray alloc]init];
        self.answerArr = [[NSMutableArray alloc]init];
        
        for (NSDictionary *dic in arr) {
            
            SN_NewspaperModel *model = [SN_NewspaperModel mj_objectWithKeyValues:dic];
            isCollection = model.iscollection == 0?NO:YES;
            if (model.type == 1) {
                [self.paperInfoArr addObject:model];
            }else if (model.type == 2) {
                [self.answerArr addObject:model];
            }
        }
        
        
        SN_NewspaperModel *paperModel = [self.paperInfoArr firstObject];
        learing = paperModel.learing1;
        courseId = paperModel.courseid;
        
        self.navBar.navigationItem.title = [NSString stringWithFormat:@"第%ld期 %@",(long)paperModel.phase,paperModel.newsname];
        
        [collectBtn setImage:[UIImage imageNamed:paperModel.iscollection == 1?@"isCollection":@"unCollection"] forState:(UIControlStateNormal)];
        
        self.paperScrollView.contentSize = CGSizeMake(SCREENWIDTH*self.paperInfoArr.count, SCREENHEIGH-SafeAreaTopHeight - 53);
        
        for (int i = 0; i<self.paperInfoArr.count; i++){
            
            SN_NewspaperModel *model = [self.paperInfoArr objectAtIndex:i];
            
            UITapGestureRecognizer *doubleTap =[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleDoubleTap:)];
            [doubleTap setNumberOfTapsRequired:2];
            
            UIScrollView *s = [[UIScrollView alloc] initWithFrame:CGRectMake(SCREENWIDTH*i, 0, SCREENWIDTH, SCREENHEIGH-64)];
            s.backgroundColor = [UIColor clearColor];
            s.contentSize = CGSizeMake(SCREENWIDTH, SCREENHEIGH-SafeAreaTopHeight);
            s.delegate = self;
            s.minimumZoomScale = 1.0;
            s.maximumZoomScale = 3.0;
            
            [s setZoomScale:1.0];
            
            UIImageView *imageview = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, SCREENWIDTH, SCREENHEIGH-SafeAreaTopHeight- 53)];
            NSString *imageName = [NSString stringWithFormat:@"%@%ld",IMAGEHOSTURL,(long)model.pic];
            
            SDLoopProgressView *loop = [SDLoopProgressView progressView];
            loop.frame = CGRectMake(0, 0, 70, 70);
            loop.center = self.view.center;
            loop.centerY -= 30;
            [imageview addSubview:loop];
            
            
            [imageview sd_setImageWithURL:[NSURL URLWithString:imageName] placeholderImage:nil options:SDWebImageCacheMemoryOnly progress:^(NSInteger receivedSize, NSInteger expectedSize, NSURL * _Nullable targetURL) {
                
                float currentProgress = (float)receivedSize/(float)expectedSize;
                currentProgress = currentProgress < 0.0001?0:currentProgress;
                loop.progress = currentProgress;

                
            } completed:^(UIImage * _Nullable image, NSError * _Nullable error, SDImageCacheType cacheType, NSURL * _Nullable imageURL) {
                [loop dismiss];
            }];
           
            imageview.userInteractionEnabled = YES;
            imageview.tag = i+1;
            [imageview addGestureRecognizer:doubleTap];
            [s addSubview:imageview];
            
            [self.paperScrollView addSubview:s];
            
        }
        self.paperScrollView.hidden = NO;
        
        if (courseId == 3 && learing.length > 0 && ![learing isEqualToString:@"0"]) {
            
           [self creatBottomView:NO];
            
        }else
        {
            [self creatBottomView:YES];
        }
        
        
        
    } failure:^(NSInteger recode, NSError *error) {
        
        collectBtn.hidden = YES;
        [self.networkErrorView showEmptyImage];
    }];
}

- (void)reloadImg:(UIImageView *)imageView url:(NSURL *)url {
    
    [imageView sd_setImageWithURL:url completed:^(UIImage * _Nullable image, NSError * _Nullable error, SDImageCacheType cacheType, NSURL * _Nullable imageURL) {
        if (!image) {
//            NSLog(@"重新加载");
//            [self reloadImg:imageView url:url];
            
            UIImageView *emptyImg = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, 180, 140)];
            [emptyImg setImage:[UIImage imageNamed:@"unContent"]];
            emptyImg.center = self.view.center;
            
            [self.answerScroll addSubview:emptyImg];

            
        }
    }];
}

- (void)collectionAction {
    
    NSMutableDictionary *param = [[NSMutableDictionary alloc]init];
    [param setObject:@"api_szb_setnewscollection" forKey:@"Method"];
    [param setObject:self.newsid forKey:@"newsid"];
    [param setObject:isCollection?@"0":@"1" forKey:@"state"];
    [param setObject:USERID forKey:@"userid"];
    
    [Utils getWithparameters:param showHUD:YES success:^(NSInteger recode, id jsonObject) {
        
        isCollection = !isCollection;
        
        [collectBtn setImage:[UIImage imageNamed:isCollection?@"isCollection":@"unCollection"] forState:(UIControlStateNormal)];
        
        [self showHint:isCollection?@"收藏成功":@"取消成功"];
        
    } failure:^(NSInteger recode, NSError *error) {
        
    }];
}

#pragma mark - Get

- (UIScrollView *)paperScrollView {
    
    if (_paperScrollView == nil) {
        
        _paperScrollView = [[UIScrollView alloc]initWithFrame:CGRectMake(0, SafeAreaTopHeight, SCREENWIDTH, SCREENHEIGH - SafeAreaTopHeight - 53)];
        _paperScrollView.delegate = self;
        _paperScrollView.hidden = YES;
        _paperScrollView.showsVerticalScrollIndicator = NO;
        _paperScrollView.showsHorizontalScrollIndicator = NO;
        _paperScrollView.pagingEnabled = YES;
    
    }
    return _paperScrollView;
}

- (UIScrollView *)answerScroll {
    
    if (_answerScroll == nil) {
        
        SN_NewspaperModel *model = [self.answerArr firstObject];
        
        UITapGestureRecognizer *doubleTap =[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleDoubleTap:)];
        [doubleTap setNumberOfTapsRequired:2];
        
        _answerScroll = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, SCREENWIDTH, SCREENHEIGH-SafeAreaTopHeight -53)];
        _answerScroll.backgroundColor = [UIColor whiteColor];
        _answerScroll.contentSize = CGSizeMake(SCREENWIDTH, SCREENHEIGH-SafeAreaTopHeight-53);
        _answerScroll.delegate = self;
        _answerScroll.minimumZoomScale = 1.0;
        _answerScroll.maximumZoomScale = 3.0;
        
        [_answerScroll setZoomScale:1.0];
        
        UIImageView *imageview = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, SCREENWIDTH, SCREENHEIGH-SafeAreaTopHeight-53)];
        imageview.userInteractionEnabled = YES;
        [imageview addGestureRecognizer:doubleTap];
        imageview.contentMode = UIViewContentModeScaleAspectFit;
        
        [_answerScroll addSubview:imageview];
        
        [self.paperScrollView addSubview:_answerScroll];
        
        NSString *imageName = [NSString stringWithFormat:@"%@%ld",IMAGEHOSTURL,(long)model.pic];

        SDLoopProgressView *loop = [SDLoopProgressView progressView];
        loop.frame = CGRectMake(0, 0, 70, 70);
        loop.center = self.view.center;
        loop.centerY -= 30;
        [imageview addSubview:loop];
        
        [imageview sd_setImageWithURL:[NSURL URLWithString:imageName] placeholderImage:nil options:SDWebImageCacheMemoryOnly progress:^(NSInteger receivedSize, NSInteger expectedSize, NSURL * _Nullable targetURL) {
            
            float currentProgress = (float)receivedSize/(float)expectedSize;
            currentProgress = currentProgress < 0.0001?0:currentProgress;
            loop.progress = currentProgress;
            
        } completed:^(UIImage * _Nullable image, NSError * _Nullable error, SDImageCacheType cacheType, NSURL * _Nullable imageURL) {
            
            [loop dismiss];
            if (image) {
                imageview.height = image.size.height;
                
                float i = SCREENWIDTH/image.size.width;
                _answerScroll.contentSize = CGSizeMake(SCREENWIDTH, image.size.height*i);
                [imageview setFrame:CGRectMake(0, 0, SCREENWIDTH, image.size.height*i)];
            }else {
                [self reloadImg:imageview url:[NSURL URLWithString:imageName]];
            }
        }];
    }
    return _answerScroll;
}

@end
